﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace TongCheng.API.OpenAPI.Util
{
    public class Encryption
    {
        /// <summary> 
        /// 获取字符数组的MD5加密值 
        /// </summary> 
        /// <param name="sortedArray">待计算MD5哈希值的输入字符数组</param> 
        /// <param name="key">密钥</param> 
        /// <param name="charset"></param> 
        /// <returns>输入字符数组的MD5哈希值</returns> 
        public static string GetMD5ByArray(string[] sortedArray, string key, string charset)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < sortedArray.Length; i++)
            {
                if (i == sortedArray.Length - 1)
                {
                    builder.Append(sortedArray[i]);
                }
                else
                {
                    builder.Append(sortedArray[i] + "&");
                }
            }
            builder.Append(key);
            return GetMD5(builder.ToString(), charset);
        }

        /// <summary> 
        /// MD5
        ///</summary> 
        /// <param name="input">待计算MD5哈希值的输入字符串</param> 
        /// <param name="charset">输入字符串的字符集</param> 
        /// <returns>输入字符串的MD5哈希值</returns> 
        public static string GetMD5(string input, string charset)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] data = md5.ComputeHash(Encoding.GetEncoding(charset).GetBytes(input));
            StringBuilder builder = new StringBuilder(32);
            for (int i = 0; i < data.Length; i++)
            {
                builder.Append(data[i].ToString("x2"));
            }
            return builder.ToString();
        }

        /// <summary> 
        /// 数组排序（冒泡排序法） 
        /// </summary> 
        /// <param name="originalArray">待排序字符串数组</param> 
        /// <returns>经过冒泡排序过的字符串数组</returns> 
        public static string[] BubbleSort(string[] originalArray)
        {
            int i, j;
            string temp;
            bool exchange;
            //交换标志 
            for (i = 0; i < originalArray.Length; i++) //最多做R.Length-1趟排序 
            {
                exchange = false; //本趟排序开始前，交换标志应为假 
                for (j = originalArray.Length - 2; j >= i; j--)
                {
                    //判断交换条件 
                    if (String.CompareOrdinal(originalArray[j + 1], originalArray[j]) < 0)
                    {
                        temp = originalArray[j + 1];
                        originalArray[j + 1] = originalArray[j];
                        originalArray[j] = temp;
                        exchange = true; //发生了交换，故将交换标志置为真 
                    }
                }
                if (!exchange) //本趟排序未发生交换，提前终止算法 
                {
                    break;
                }
            }
            return originalArray;
        }
    }
}

